import React, {Component} from 'react';
import ThePagination from "@/components/ThePagination";
import {Select, Tabs} from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import {
    apiStockLibraryGoodsList,
    apiStockLibraryGoodsPage,
    apiStockTakeListAddBefore,
    apiStockTakeListDel,
    apiStockTakeListPage
} from '@/request/storageManager/stock.js'
import {exportSheetTable} from '@/utils/exportTable'
import './components/style.scss'
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"

const {TabPane} = Tabs;
const {Option} = Select
const status = [{label: '草稿', value: 0, color: 'black'}, {
    label: '未审核',
    value: 1,
    color: "orange"
}, {label: '已审核', value: 2, color: "#1890ff"}, {label: '已驳回', value: 3, color: "#cccccc"}]

class Stock extends Component {
    constructor() {
        super()
        // this.formRef_check = React.createRef()
        // this.formRef_store = React.createRef()
        this.queryFormRef_check = React.createRef()
        this.queryFormRef_store = React.createRef()
        this.state = {
            columnsCheck: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render: (text, record, index) => {
                        return ((this.state.pageDataCheck.pageNo - 1) * (this.state.pageDataCheck.pageSize) + (index + 1));
                    }
                },
                {
                    title: "盘点单号",
                    dataIndex: "code",
                    key: "code",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "盘点日期",
                    dataIndex: "createTime",
                    key: "createTime",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "仓库名称",
                    dataIndex: "libraryName",
                    key: "libraryName",
                    render: (text, render) => {
                        return text
                    }
                },
                // {
                //     title: "盈亏量",
                //     dataIndex: "sum",
                //     key: "sum",
                //     render: (text, render) => {
                //         return text
                //     }
                // },
                {
                    title: "登记人",
                    dataIndex: "userName",
                    key: "userName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "审批人",
                    dataIndex: "checkName",
                    key: "checkName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "审批时间",
                    dataIndex: "checkedTime",
                    key: "checkedTime",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text, render) => {
                        let obj = status.find(item => item.value == text);

                        return obj === undefined ? '' : <div style={{color: obj.color}}>
                            {obj.label}
                        </div>
                    }
                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:stockCheck:view']}
                                       onClick={() => this.opreate('normal', render.id)}>查看详情</TheButton>
                            {
                                render.status === 0 &&
                                <TheButton haspermi={['storage:stockCheck:edit']}
                                           onClick={() => this.opreate('edit', render.id)}>编辑</TheButton>

                            }
                            {
                                render.status === 1 ?
                                    <TheButton haspermi={['storage:stockCheck:execute']}
                                               onClick={() => this.opreate('execute', render.id)}>审核</TheButton> : null
                            }
                            {
                                render.status === 0 && <TheButton haspermi={['storage:stockCheck:del']}
                                                                  onClick={() => this.del(render.id)}>删除</TheButton>
                            }

                        </div>
                    }
                },
            ],
            newColumns_check: [],
            form_show_check: true,
            searchOption_check: [
                {
                    field: 'code',
                    label: '盘点单号',
                    placeholder: '盘点单号',
                    required: false,
                    rules: [],
                    type: 'Input',
                    defaultValue: ''
                },

                {
                    field: 'libraryName',
                    label: '仓库名称',
                    placeholder: '仓库名称',
                    required: false,
                    rules: [],
                    type: 'Input',
                    options: [],
                    defaultValue: ''
                },
                // { field: 'status', label: '状态', placeholder: '状态', required: false, rules: [], type: 'Select', options: status, defaultValue: '' },
            ],
            queryForm_check: {},
            dataSourceCheck: [],
            totalCheck: 0,
            libraryName_check: '',
            librarys: [],
            pageDataCheck: {
                pageNo: 1,
                pageSize: 10
            },
        }
    }

    componentDidMount() {
        this.setState({
            newColumns_check: this.state.columnsCheck
        })
        let searchParams = store.getState().searchValue
        let {queryForm_check, pageNoC, pageSizeC, pathName} = searchParams

        this.queryFormRef_check.onSetDefault({
            ...queryForm_check
        })

        if (searchParams && pageNoC&&pathName == 'stockTake') {
            this.setState({
                queryForm_check,
                pageDataCheck: {
                    pageNo: pageNoC, pageSize: pageSizeC
                }

            }, () => {
                this.getLibrarys()
                this.getCheckPage()
            })
        } else {
            this.getLibrarys()
            this.getCheckPage()
        }


    }

    opreate(type, id) {
        this.props.history.push('/stockManager/stockTake/' + id + "/" + type)
    }

    async getLibrarys() {
        let res = await apiStockTakeListAddBefore()
        if (res.code === 0) {
            console.log(res.data.librarys);
            // this.state.searchOption_store[0].options = res.data.librarys
            this.setState({
                librarys: res.data.librarys,
                // searchOption_store: this.state.searchOption_store
            })
        }
    }

    // 盘点
    getCheckPage(values) {
        this.setState({
            queryForm_check: values === undefined ? this.state.queryForm_check : {...values}
        }, async () => {
            let {pageNo, pageSize} = this.state.pageDataCheck
            let params = {
                pageNoC: this.state.pageDataCheck.pageNo,
                pageSizeC: this.state.pageDataCheck.pageSize,
                queryForm_check: this.state.queryForm_check,
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'stockTake',
                    ...params
                }
            })
            let res = await apiStockTakeListPage({pageNo, pageSize, ...this.state.queryForm_check})
            if (res.code === 0) {
                this.setState({
                    dataSourceCheck: res.data,
                    totalCheck: res.totalCount
                })
            }
        })

    }

    pageChangeCheck = (pageNo, pageSize) => {
        this.setState({
            // libraryName_check: values.libraryName?values.libraryName:null,
            pageDataCheck: {
                pageNo, pageSize
            }
        }, () => {
            this.getCheckPage()
        })
    };
    onReset_check = () => {
        this.setState({
            queryForm_check: {}
        }, () => {

            this.pageChangeCheck(1, 10)
        })
    }

    async del(id) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockTakeListDel({id})
                if (res.code === 0) {
                    this.pageChangeCheck(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });

    }


    getGoodsStatus = (value) => {
        switch (value) {
            case 'Y':
                return "上架"
            case 'N':
                return "下架"
            case 'G':
                return "管理员下架"
            default:
                return '/'
        }
    }

    export = async () => {
        let tH_data, tB_data
        tH_data = [
            {prop: 'libraryName', title: '仓库名称'},
            {prop: 'goodsSkuNo', title: '物品编码'},
            {prop: 'goodsName', title: '物品名称'},
            {prop: 'sku', title: '规格'},
            {prop: 'goodsStatus', title: '上架状态'},
            {prop: 'minCount', title: '库存下限', valueType:'number'},
            {prop: 'count', title: '库存量', valueType:'number'},
            {prop: 'waiteOutCount', title: '待出库', valueType:'number'},
        ]
        let values = this.state.queryForm_store
        console.log(values);
        let res = await apiStockLibraryGoodsList({
            "goodsName": values && values.goodsName ? values.goodsName : '',
            libraryId: values && values.libraryId ? values.libraryId : '',
            materialId: values && values.materialId ? values.materialId : "",
            goodsStatus: values && values.goodsStatus ? values.goodsStatus : ""
        })
        if (res.code === 0 && res.data && res.data.length > 0) {
            tB_data = res.data.map(item => {
                return {
                    ...item,
                    goodsStatus: this.getGoodsStatus(item.goodsStatus),
                    minCount: item.minCount == -1 ? '不限制' : item.minCount,
                    row_bgColor: item.count < item.minCount ? '#e8b300' : ''
                }
            })
            exportSheetTable({
                fileName: '库存管理', tH_data, tB_data: tB_data, isSheet: true, merge: false
            })
        }

    }

    rowClassName(record, index) {

        if (record.minCount > record.count) {
            return 'warning'
        }
        return ''
    }

    onChange(e) {
        let params = {
            tab: e
        }
        store.dispatch({
            type: 'SavePageTabValue',
            data: {
                ...params
            }
        })

        this.queryFormRef_check.onSetDefault({
            ...this.state.queryForm_check
        })
    }

    onFormSearch_check(values) {
        this.setState({
            pageDataCheck: {pageNo: 1, pageSize: 10}
        }, () => {
            this.getCheckPage(values)
        })
    }

    render() {
        let {
            columnsCheck,
            librarys, dataSourceCheck, pageDataCheck, totalCheck,
            form_show_check, searchOption_check, newColumns_check

        } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef_check = ref} show={form_show_check}
                              option={searchOption_check}
                              onReset={() => this.onReset_check()}
                              onGetValues={(values) => this.onFormSearch_check(values)}>
                </TheQueryForm>
                <TheTableExtend
                    columns={columnsCheck}
                    onFormTrigger={() => this.setState({form_show_check: !this.state.form_show_check})}
                    onTableRefresh={() => this.getCheckPage()}
                    onColumnsFilter={(value) => this.setState({
                        newColumns_check: value
                    })}
                >
                    <TheButton haspermi={['storage:stockCheck:add']} size="middle"
                               onClick={() => this.props.history.push('/storageManager/takeStock/null/add')}
                               type="primary">新增</TheButton>

                </TheTableExtend>
                <TheTable
                    scroll={{x: "max-content", y: '63vh'}}
                    columns={newColumns_check}
                    dataSource={dataSourceCheck}
                />
                <ThePagination
                    pageNo={pageDataCheck.pageNo}
                    pageSize={pageDataCheck.pageSize}
                    total={totalCheck}
                    pageChange={this.pageChangeCheck}
                />
            </div>
        );
    }
}

export default Stock
